﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using CkSoftware.GroupMeChatModule.Constants;
using DotNetNuke.Entities.Modules;

namespace CkSoftware.GroupMeChatModule.Managers
{
	public class ModuleSettingsManager
	{
		private readonly int _moduleId;
		private readonly Hashtable _settings;

		public string GroupMeGroupId
		{
			get { return GetSettingValueOrDefault<string>(ModulePropertyKeys.GroupMeGroupId); }
			set { SetOrUpdateSettingValue(ModulePropertyKeys.GroupMeGroupId, value); }
		}

		public string MessageLoadUserAccessToken
		{
			get { return GetSettingValueOrDefault<string>(ModulePropertyKeys.MessageLoadUserAccessToken); }
			set { SetOrUpdateSettingValue(ModulePropertyKeys.MessageLoadUserAccessToken, value); }
		}

		public string GroupMeAuthRedirectUrl
		{
			get { return GetSettingValueOrDefault<string>(ModulePropertyKeys.GroupMeAuthRedirectUrl); }
			set { SetOrUpdateSettingValue(ModulePropertyKeys.GroupMeAuthRedirectUrl, value); }
		}

		public string ShowMessageBoxOnBottom
		{
			get { return GetSettingValueOrDefault<string>(ModulePropertyKeys.ShowMessageBoxOnBottom, false.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); }
			set { SetOrUpdateSettingValue(ModulePropertyKeys.ShowMessageBoxOnBottom, value); }
		}

		public string MessagesHeight
		{
			get { return GetSettingValueOrDefault<string>(ModulePropertyKeys.MessagesHeight, "625"); }
			set { SetOrUpdateSettingValue(ModulePropertyKeys.MessagesHeight, value);}
		}

		public ModuleSettingsManager(int moduleId)
		{
			_moduleId = moduleId;
			_settings = (new ModuleController().GetModuleSettings(moduleId));
		}

		public void Save()
		{
			var moduleController = new ModuleController();
			moduleController.UpdateModuleSetting(_moduleId, ModulePropertyKeys.GroupMeAuthRedirectUrl, GroupMeAuthRedirectUrl);
			moduleController.UpdateModuleSetting(_moduleId, ModulePropertyKeys.GroupMeGroupId, GroupMeGroupId);
			moduleController.UpdateModuleSetting(_moduleId, ModulePropertyKeys.MessageLoadUserAccessToken, MessageLoadUserAccessToken);
			moduleController.UpdateModuleSetting(_moduleId, ModulePropertyKeys.ShowMessageBoxOnBottom, ShowMessageBoxOnBottom);
			moduleController.UpdateModuleSetting(_moduleId, ModulePropertyKeys.MessagesHeight, MessagesHeight);
		}

		public override int GetHashCode()
		{
			return GroupMeAuthRedirectUrl.GetHashCode() ^ GroupMeGroupId.GetHashCode() ^ MessageLoadUserAccessToken.GetHashCode();
		}

		private T GetSettingValueOrDefault<T>(string key, T defaultValue = default(T))
		{
			return _settings.ContainsKey(key) ? (T) _settings[key] : defaultValue;
		}

		private void SetOrUpdateSettingValue(string key, object newValue)
		{
			if (_settings.ContainsKey(key))
			{
				_settings[key] = newValue;
			}
			else
			{
				_settings.Add(key, newValue);
			}
		}
	}
}